using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.DTOS;
using SmartLink.DTOS.SysBasic;
using SmartLink.Application.IServices;
using SmartLink.Domain;
using SmartLink.Domain.Entity;
using SmartLink.Domain.ExpandEntity.Base;
using SmartLink.Domain.ExpandEntity.Oragnization;
using SmartLink.Domain.Services;
using SmartLink.EnumLibrary;
using SmartLink.Infrastructure;
using SmartLink.Infrastructure.Cache;
using SmartLink.IRepository;
using SmartLink.Domain.IServices;
using SmartLink.Domain.ExpandEntity;
using SmartLink.DTOS.Smart;

namespace SmartLink.Application.Services
{
    public class SysBasicAppServices : ISysBasicAppServices
    {
        //组织机构
        private IBIZ_OrganizationServices _BIZ_OrganizationServices;
        //组织机构(部门)
        private IBIZ_OrganizationDepartmentServices _BIZ_OrganizationDeptServices;
        private ISysBasicServices _ISysBasicServices;
        private ISys_ParamSettingRepo _ISys_ParamSettingRepo;


        public SysBasicAppServices(IBIZ_OrganizationServices iBIZ_OrganizationServices,
                                   IBIZ_OrganizationDepartmentServices iBIZ_OrganizationDepartmentServices,
                                   ISysBasicServices isysBasicServices,
                                   ISys_ParamSettingRepo iSys_ParamSettingRepo)
        {
            _BIZ_OrganizationServices = iBIZ_OrganizationServices;
            _BIZ_OrganizationDeptServices = iBIZ_OrganizationDepartmentServices;
            _ISysBasicServices = isysBasicServices;

            _ISys_ParamSettingRepo = iSys_ParamSettingRepo;
        }


        #region 组织机构

        public Results AddOrganization(InOrganizationDTO inOrganizationDTO)
        {
            var organization = Mapper.Map<BIZ_Organization>(inOrganizationDTO);
            bool existOrgName = _BIZ_OrganizationServices.CheckExistByOrgName(inOrganizationDTO.OrganizationName);
            if (existOrgName)
                return InfrastructureAppService.Response("公司名称已经存在！", StateCodeEnum.失败.GetHashCode());
            var opResult = _BIZ_OrganizationServices.AddOrganization(organization);
            return InfrastructureAppService.Transmit(opResult);
        }

        public Results DeleteOrganization(DeleteIDDto deleteIDDto)
        {
            bool sucFlag = false;

            sucFlag = _BIZ_OrganizationServices.DeleteOrganization(deleteIDDto.ID);
            if (sucFlag)
                return InfrastructureAppService.Response("删除成功", StateCodeEnum.成功.GetHashCode());
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        /// <summary>
        /// 更新组织
        /// </summary>
        /// <param name="OrganizationDTO"></param>
        /// <returns></returns>

        public Results UpdateOrganization(UpdateOrganizationDTO updateOrganizationDTO)
        {
            bool sucFlag = false;
            if (updateOrganizationDTO.ParentID <= 0) updateOrganizationDTO.ParentID = null;
            BIZ_Organization originalOrg = _BIZ_OrganizationServices.GetSingleOrganization(updateOrganizationDTO.ID);
            if (originalOrg.OrganizationName != updateOrganizationDTO.OrganizationName)
            {
                bool existOrgName = _BIZ_OrganizationServices.CheckExistByOrgName(updateOrganizationDTO.OrganizationName);
                if (existOrgName)
                    return InfrastructureAppService.Response("公司名称已经存在！", StateCodeEnum.失败.GetHashCode());
            }

            Mapper.Map(updateOrganizationDTO, originalOrg, typeof(UpdateOrganizationDTO), typeof(BIZ_Organization));
            sucFlag = _BIZ_OrganizationServices.UpdateOrganization(originalOrg);

            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        /// <summary>
        /// 组织机构列表（分页）
        /// </summary>
        /// <param name="PagePara"></param>
        /// <returns></returns>
        public Results<PageData<OrganizationDTO>> GetOrganizationList(OrganizationPagePara PagePara)
        {
            var count = 0;
            var pageData = new PageData<OrganizationDTO>();
            var dtoList = new List<OrganizationDTO>();

            var organizations = _BIZ_OrganizationServices.GetOrganizationList(PagePara.OrganizationStatus, PagePara.OrganizationDistrict, PagePara.KeyValue, PagePara.PageIndex, PagePara.PageSize, PagePara.IsSearchTotal, out count);
            Mapper.Map(organizations, dtoList, typeof(IList<OrganizationManageExpand>), typeof(List<OrganizationDTO>));

            pageData.CurrentData = dtoList;
            pageData.TotalCount = count;

            return InfrastructureAppService.Response<PageData<OrganizationDTO>>(pageData);
        }
        /// <summary>
        /// 组织机构列表（不分页）
        /// </summary>
        /// <returns></returns>
        public Results<IList<OrganizationNoPageDTO>> OrganizationListinfo()
        {
            IList<OrganizationNoPageDTO> supperdto = new List<OrganizationNoPageDTO>();
            IList<BIZ_Organization> list = _BIZ_OrganizationServices.OrganizationListinfo();
            Mapper.Map(list, supperdto, typeof(IList<BIZ_Organization>), typeof(IList<OrganizationNoPageDTO>));
            return InfrastructureAppService.Response(supperdto);
        }

        /// <summary>
        /// 获取组织机构信息
        /// </summary>
        /// <param name="getIDDTO"></param>
        /// <returns></returns>
        public Results<UpdateOrganizationDTO> GetSingleOrganization(GetIDDTO getIDDTO)
        {
            SingleOragnizationInfoExapnd organization = _BIZ_OrganizationServices.GetSingleOrganization(getIDDTO.ID);
            UpdateOrganizationDTO organizationDto = AutoMapper.Mapper.Map<SingleOragnizationInfoExapnd, UpdateOrganizationDTO>(organization);

            return InfrastructureAppService.Response(organizationDto);
        }

        public Results UpdateOrgStatus(UpdateOrgStatus updateOrgStatus)
        {
            BIZ_Organization organization = _BIZ_OrganizationServices.GetSingleOrganization(updateOrgStatus.ID);
            organization.OrganizationStatus = updateOrgStatus.OrganizationStatus;
            bool sucFlag = _BIZ_OrganizationServices.UpdateOrganization(organization);

            if (updateOrgStatus.OrganizationStatus == (int)OrgStatusEnum.禁用)
                DisabledCompanysCache.AddDisabledCompany(updateOrgStatus.ID);
            else
                DisabledCompanysCache.RemoveDisabledCompany(updateOrgStatus.ID);

            if (sucFlag)
                return InfrastructureAppService.Response(StateCodeEnum.成功.ToString(), StateCodeEnum.成功.GetHashCode());
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        public static bool InitDisabledCompanysCache()
        {
            var result = BIZ_OrganizationServices.InitDisabledCompanyIds();
            return result;
        }

        #endregion

        #region 组织架构 (部门)

        public Results<PageData<OrganizationDeptDTO>> GetOrganizationDeptList(OrganizationDeptPagePara pagePara)
        {
            var pagination = pagePara.ToPagination();
            var oid = pagePara.OID.HasValue ? pagePara.OID.Value : CurrentUser.Current.OID;
            var organizations = _BIZ_OrganizationDeptServices.GetOrganizationDeptList(oid, pagePara.KeyValue, pagination);
            var organizationDeptDtos = Mapper.Map<IList<OrganizationDeptDTO>>(organizations);
            var pageData = new PageData<OrganizationDeptDTO>
            {
                CurrentData = organizationDeptDtos,
                TotalCount = pagination.TotalCount
            };
            return InfrastructureAppService.Response(pageData);
        }



        public Results AddOrganizationDept(InOrganizationDeptDTO department, int userId, int curUserOid)
        {
            bool existDeptName = _BIZ_OrganizationDeptServices.CheckExistByDeptName(department.OID, department.DepartmentName);
            if (existDeptName)
                return InfrastructureAppService.Response("该公司下已有相同部门！", StateCodeEnum.失败.GetHashCode());
            bool exsitDeptShortName = _BIZ_OrganizationDeptServices.CheckExistByDeptName(department.OID, department.DepartmentShorterName);
            if (exsitDeptShortName)
                return InfrastructureAppService.Response("该公司下已有相同的部门简称", StateCodeEnum.失败.GetHashCode());
            BIZ_OrganizationDepartment organizationDept = Mapper.Map<InOrganizationDeptDTO, BIZ_OrganizationDepartment>(department);
            _BIZ_OrganizationDeptServices.AddOrganizationDept(organizationDept, userId, curUserOid);
            return InfrastructureAppService.Response();
        }

        public Results DeleteOrganizationDept(DeleteIDDto deleteIDDto)
        {
            bool sucFlag = false;
            string msg = "";
            sucFlag = _BIZ_OrganizationDeptServices.DeleteOrganizationDept(deleteIDDto.ID, out msg);
            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(msg.Length > 0 ? msg : StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        /// <summary>
        /// 更新组织架构（部门）
        /// </summary>
        /// <param name="OrganizationDTO"></param>
        /// <returns></returns>

        public Results UpdateOrganizationDept(UpdateOrganizationDeptDTO updateOrganizationDeptDTO, int userId)
        {
            bool sucFlag = false;
            if (updateOrganizationDeptDTO.ParentID <= 0) updateOrganizationDeptDTO.ParentID = null;
            BIZ_OrganizationDepartment originalDept = _BIZ_OrganizationDeptServices.GetSingleOrganizationDept(updateOrganizationDeptDTO.ID);
            if (originalDept.DepartmentName != updateOrganizationDeptDTO.DepartmentName)
            {
                bool exsitDeptName = _BIZ_OrganizationDeptServices.CheckExistByDeptName(originalDept.OID, updateOrganizationDeptDTO.DepartmentName);
                if (exsitDeptName)
                    return InfrastructureAppService.Response("已经存在相同的部门名称", StateCodeEnum.失败.GetHashCode());

            }
            if (originalDept.DepartmentShorterName != updateOrganizationDeptDTO.DepartmentShorterName)
            {
                bool exsitDeptShortName = _BIZ_OrganizationDeptServices.CheckExistByDeptName(originalDept.OID, updateOrganizationDeptDTO.DepartmentShorterName);
                if (exsitDeptShortName)
                    return InfrastructureAppService.Response("已经存在相同的部门简称", StateCodeEnum.失败.GetHashCode());
            }

            if (originalDept != null)
            {
                //Mapper.Map(updateOrganizationDeptDTO, originalDept, typeof(UpdateOrganizationDeptDTO), typeof(BIZ_OrganizationDepartment));
                originalDept.DepartmentName = updateOrganizationDeptDTO.DepartmentName;
                originalDept.DepartmentShorterName = updateOrganizationDeptDTO.DepartmentShorterName;
                originalDept.Contact = updateOrganizationDeptDTO.Contact;
                originalDept.Phone = updateOrganizationDeptDTO.Phone;
                originalDept.ParentID = updateOrganizationDeptDTO.ParentID;
                originalDept.Extension = updateOrganizationDeptDTO.Extension;
                originalDept.DepartmentRemark = updateOrganizationDeptDTO.DepartmentRemark;
                originalDept.Updater = userId;
                originalDept.UpdateTime = DateTime.Now;
                sucFlag = _BIZ_OrganizationDeptServices.UpdateOrganizationDept(originalDept);
            }
            if (sucFlag)
                return InfrastructureAppService.Response();
            else
                return InfrastructureAppService.Response(StateCodeEnum.失败.ToString(), StateCodeEnum.失败.GetHashCode());
        }

        public Results<OrganizationDeptDTO> GetSingleOrganizationDept(GetIDDTO getIDDTO)
        {
            BIZ_OrganizationDepartment organizationDept = _BIZ_OrganizationDeptServices.GetSingleOrganizationDept(getIDDTO.ID);
            var organizationDeptDto = AutoMapper.Mapper.Map<BIZ_OrganizationDepartment, OrganizationDeptDTO>(organizationDept);
            if (organizationDeptDto == null)
            {
                return InfrastructureAppService.Response<OrganizationDeptDTO>(StateCodeEnum.数据为空.ToString(), StateCodeEnum.失败.GetHashCode());
            }
            //赋上 父部门
            //if (organizationDept.ParentID == -1)
            //{
            //    BIZ_Organization parentOrg = _BIZ_OrganizationServices.GetSingleOrganization(organizationDept.OID);
            //    organizationDeptDto.ParentDeptName = parentOrg.OrganizationName;
            //}
            //else
            //{
            //    BIZ_OrganizationDepartment parentDept = _BIZ_OrganizationDeptServices.GetSingleOrganizationDept(organizationDept.ParentID);
            //    organizationDeptDto.ParentDeptName = parentDept.DepartmentName;
            //}
            return InfrastructureAppService.Response(organizationDeptDto);
        }



        public Results<IList<OrganizationDeptDTO>> GetAllStoreByOrgId(int orgId)
        {
            IList<BIZ_OrganizationDepartment> organizationDepts = _BIZ_OrganizationDeptServices.GetAllStoreByOrgId(orgId);
            if (organizationDepts == null || organizationDepts.Count == 0)
            {
                return InfrastructureAppService.Response<IList<OrganizationDeptDTO>>(new List<OrganizationDeptDTO>(), StateCodeEnum.数据为空.ToString(), StateCodeEnum.成功.GetHashCode());
            }
            var organizationDeptDtos = AutoMapper.Mapper.Map<IList<BIZ_OrganizationDepartment>, IList<OrganizationDeptDTO>>(organizationDepts);

            return InfrastructureAppService.Response(organizationDeptDtos);
        }


        /// <summary>
        /// 获取部门树 1，传递了oid，获取公司下的部门树，
        ///           2, 没传递，a: 公司管理员：获取当前用户下的公司id下的部门树 
        ///                     b: 公司一般用户 根据当前部门id，因为不能看到上级部门
        ///                   
        /// </summary>
        /// <param name="getIDDTO"></param>
        /// <returns></returns>
        public Results<CompanyNode> GetDepartmentTree(int? oid)
        {
            if (!oid.HasValue) oid = CurrentUser.Current.OID;
            var depts = _BIZ_OrganizationDeptServices.GetAllDeptByOrgId(oid.Value);
            var org = _BIZ_OrganizationServices.GetOrganization(oid.Value);
            var treeData = CenarateDepartmentTreeOfCompany(depts, org);
            return InfrastructureAppService.Response(treeData);
        }



        private CompanyNode CenarateDepartmentTreeOfCompany(IList<BIZ_OrganizationDepartment> depts, BIZ_Organization company)
        {
            var treeRoot = new CompanyNode
            {
                ID = company.ID,
                Name = company.OrganizationShorterName,
                IsDept = false,
                SequenceId = company.ID
            };
            var deptsNodes = GenarateDeptTreesForCompanyTree(depts);
            treeRoot.SubLinks = deptsNodes;
            return treeRoot;
        }

        private void SetChildNodes(DeptTreeNode node, Dictionary<int, List<DeptTreeNode>> dic)
        {
            if (!dic.Keys.Contains(node.ID))
            {
                return;
            }
            node.SubDepts = dic[node.ID];
            foreach (var item in node.SubDepts)
            {
                SetChildNodes(item, dic);
            }
        }

        #endregion

        #region 获取字典

        /// <summary>
        /// 根据字典类型字符串获取字典list
        /// </summary>
        /// <param name="categorys"></param>
        /// <returns></returns>
        public Results<Dictionary<string, List<DictionaryDTO>>> ArrayDictionaryList(string categorys)
        {
            var dtoDid = new Dictionary<string, List<DictionaryDTO>>();
            var categoryArr = categorys.Split(',');
            foreach (var item in categoryArr)
            {
                var dtoList = new List<DictionaryDTO>();
                var intItem = item.ToString();
                var list = _ISysBasicServices.DictionaryList(item);
                AutoMapper.Mapper.Map(list, dtoList, typeof(List<SYS_Dictionary>), typeof(List<DictionaryDTO>));
                dtoDid[intItem] = dtoList;
            }

            return InfrastructureAppService.Response(dtoDid);
        }

        /// <summary>
        /// 获取字典
        /// </summary>
        /// <returns></returns>
        public Results<List<DictionaryDTO>> DictionaryList(string categoryValue)
        {
            var dtoList = new List<DictionaryDTO>();
            var list = _ISysBasicServices.DictionaryList(categoryValue);
            AutoMapper.Mapper.Map(list, dtoList, typeof(List<SYS_Dictionary>), typeof(List<DictionaryDTO>));
            return InfrastructureAppService.Response(dtoList);
        }

        /// <summary>
        /// 获取所有字典
        /// </summary>
        /// <returns></returns>
        public Results<List<DictionaryDTO>> GetAllDic()
        {
            var dtoList = new List<DictionaryDTO>();
            var list = new List<DictionaryDTO>();   // _vehvehicleService.GetAllDic();
            AutoMapper.Mapper.Map(list, dtoList, typeof(SYS_Dictionary), typeof(DictionaryDTO));
            return InfrastructureAppService.Response(dtoList);
        }

        public Results AddDictionary(DictionaryDTO model, int creator)
        {
            var dictionary = Mapper.Map<SYS_Dictionary>(model);
            dictionary.Creator = creator;
            dictionary.CreateTime = DateTime.Now;
            var opResult = _ISysBasicServices.AddDictionary(dictionary);
            return InfrastructureAppService.Transmit(opResult);
        }

        #endregion

        #region 

        /// <summary>
        /// 获取公司的树结构
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public Results<CompanyNode> GetCompanyTree(int UserId, TreeFlagDTO treeFlagDTO)
        {
            CompanyNode reNode = new CompanyNode();
            reNode.ID = -1;
            reNode.SequenceId = -1;
            reNode.SubLinks = new List<CompanyNode>();
            CurrentUserInfo curUserInfo = UserInfoCaches.GetUserInfoCache(UserId);
            if (treeFlagDTO.TransferIndex == 0)
            {

                if (curUserInfo.RoleName == ConstData.SuperManagerRoleName)
                {
                    reNode.Name = "所有公司";
                    IList<BIZ_Organization> allOrgs = _BIZ_OrganizationServices.OrganizationListinfo();
                    foreach (BIZ_Organization org in allOrgs)
                    {
                        CompanyNode curCompanyNode = GetSingleOrgTree(org.ID);
                        reNode.SubLinks.Add(curCompanyNode);
                    }
                }
                else
                {
                    reNode.Name = curUserInfo.OrganizationName;
                    reNode = GetSingleOrgTree(curUserInfo.OID);
                }
            }
            else if (treeFlagDTO.TransferIndex == 1)
            {
                reNode.Name = curUserInfo.OrganizationName;
                reNode = GetSingleOrgTree(curUserInfo.OID);
            }
            else
            {
                reNode.Name = "所有公司";
                IList<BIZ_Organization> allOrgs = _BIZ_OrganizationServices.OrganizationListinfo();
                foreach (BIZ_Organization org in allOrgs)
                {
                    CompanyNode curCompanyNode = GetSingleOrgTree(org.ID);
                    reNode.SubLinks.Add(curCompanyNode);
                }
            }

            return InfrastructureAppService.Response(reNode);
        }

        public Results<CompanyNode> GetOrgTree(int? oid = null, bool toRoot = false)
        {
            CompanyNode tree = null;
            if (CurrentUser.IsSuperAdmin && !oid.HasValue)
            {
                tree = new CompanyNode
                {
                    ID = -1,
                    SequenceId = -1,
                    Name = "所有公司",
                    IsDept = false,
                    SubLinks = new List<CompanyNode>()
                };
                var rootOrgs = _BIZ_OrganizationServices.GetRootOrganizations();
                foreach (var rootOrg in rootOrgs)
                {
                    var rootOrgTree = GetSingleOrgTree(rootOrg.ID);
                    tree.SubLinks.Add(rootOrgTree);
                }
            }
            else if (CurrentUser.IsOrgAdmin && !oid.HasValue)
            {
                oid = CurrentUser.Current.ROID;
                tree = GetSingleOrgTree(oid.Value);
            }
            else
            {
                if (!oid.HasValue) oid = CurrentUser.Current.OID;
                if (toRoot) oid = CurrentUser.Current.ROID;
                tree = GetSingleOrgTree(oid.Value);
            }
            return InfrastructureAppService.Response(tree);
        }


        public CompanyNode GetSingleOrgTree(int oid)
        {
            var companyList = _BIZ_OrganizationServices.GetOrgDescendants(oid, true);
            var topNode = companyList.SingleOrDefault(a => a.ID == oid);
            var treeNode = new CompanyNode
            {
                ID = topNode.ID,
                Name = topNode.OrganizationShorterName,
                SequenceId = topNode.ID,
                IsDept = false,
            };
            SetChildCompanyNodes(treeNode, companyList);

            TraverseCompanyTreeAddDepartments(treeNode);

            return treeNode;
        }

        private void TraverseCompanyTreeAddDepartments(CompanyNode companyNode)
        {
            var depts = _BIZ_OrganizationDeptServices.GetAllDeptByOrgId(companyNode.ID);
            IList<CompanyNode> deptFakeTrees = GenarateDeptTreesForCompanyTree(depts);
            if (companyNode.SubLinks == null) companyNode.SubLinks = new List<CompanyNode>();
            companyNode.SubLinks = companyNode.SubLinks.Concat(deptFakeTrees).ToList();

            var childCompanies = companyNode.SubLinks.Where(a => a.IsDept == false).ToList();
            foreach (var childCompany in childCompanies)
            {
                TraverseCompanyTreeAddDepartments(childCompany);
            }
        }

        private IList<CompanyNode> GenarateDeptTreesForCompanyTree(IList<BIZ_OrganizationDepartment> deptList)
        {
            var topDepts = deptList.Where(a => !a.ParentID.HasValue).OrderBy(a => a.Sort).ToList();
            var topDeptsNodes = Mapper.Map<List<CompanyNode>>(topDepts);
            var topDeptsChildrenDic = deptList.Where(a => a.ParentID.HasValue).GroupBy(a => a.ParentID.Value)
                .ToDictionary(a => a.Key, a => Mapper.Map<List<CompanyNode>>(a.OrderBy(b => b.Sort).ToList()));
            foreach (var topDeptNode in topDeptsNodes)
            {
                AppendDeptTreeChildNodesForCompanyTree(topDeptNode, topDeptsChildrenDic);
            }
            return topDeptsNodes;
        }
        private void AppendDeptTreeChildNodesForCompanyTree(CompanyNode deptFakeNode, Dictionary<int, List<CompanyNode>> allChildDeptNodesDic)
        {
            if (allChildDeptNodesDic.ContainsKey(deptFakeNode.ID))
            {
                deptFakeNode.SubLinks = allChildDeptNodesDic[deptFakeNode.ID];
                foreach (var child in deptFakeNode.SubLinks)
                {
                    AppendDeptTreeChildNodesForCompanyTree(child, allChildDeptNodesDic);
                }
            }
        }

        private void SetChildNodes(CompanyNode node, Dictionary<int, List<CompanyNode>> dic)
        {
            if (!dic.Keys.Contains(node.ID))
            {
                return;
            }
            node.SubLinks = dic[node.ID];
            foreach (var item in node.SubLinks)
            {
                SetChildNodes(item, dic);
            }
        }

        public Results<CompanyNode> GetCompanyNodeTree(int? oid = null, bool toRoot = false)
        {
            CompanyNode rootNode = null;
            if (CurrentUser.IsSuperAdmin && !oid.HasValue)
            {
                rootNode = new CompanyNode
                {
                    ID = -1,
                    Name = "所有公司",
                    SequenceId = -1,
                    IsDept = false,
                };
                var companyList = _BIZ_OrganizationServices.GetCompanyTreeData(null);
                var rootCompanys = companyList.Where(a => a.ParentID == null).OrderBy(a => a.ID).Select(a => new CompanyNode
                {
                    ID = a.ID,
                    Name = a.OrganizationShorterName,
                    SequenceId = a.ID,
                    IsDept = false,
                }).ToList();
                foreach (var rootCompany in rootCompanys)
                {
                    SetChildCompanyNodes(rootCompany, companyList);
                }
                rootNode.SubLinks = rootCompanys;
            }
            else if (CurrentUser.IsOrgAdmin && !oid.HasValue)
            {
                oid = CurrentUser.Current.ROID;
                var companyList = _BIZ_OrganizationServices.GetCompanyTreeData(oid);
                rootNode = companyList.Where(a => a.ID == oid.Value).Select(a => new CompanyNode
                {
                    ID = a.ID,
                    Name = a.OrganizationShorterName,
                    SequenceId = a.ID,
                    IsDept = false,
                }).Single();
                SetChildCompanyNodes(rootNode, companyList);
            }
            else
            {
                if (!oid.HasValue) oid = CurrentUser.Current.OID;
                if (toRoot) oid = CurrentUser.Current.ROID;
                var companyList = _BIZ_OrganizationServices.GetCompanyTreeData(oid);
                rootNode = companyList.Where(a => a.ID == oid.Value).Select(a => new CompanyNode
                {
                    ID = a.ID,
                    Name = a.OrganizationShorterName,
                    SequenceId = a.ID,
                    IsDept = false,
                }).Single();
                SetChildCompanyNodes(rootNode, companyList);
            }
            return InfrastructureAppService.Response(rootNode);
        }

        private void SetChildCompanyNodes(CompanyNode node, IEnumerable<BIZ_Organization> orgs)
        {
            var children = orgs.Where(a => a.ParentID == node.ID).Select(a => new CompanyNode
            {
                ID = a.ID,
                Name = a.OrganizationShorterName,
                SequenceId = a.ID,
                IsDept = false,
            }).ToList();
            node.SubLinks = children;
            if (node.SubLinks.Count > 0)
            {
                foreach (var item in node.SubLinks)
                {
                    SetChildCompanyNodes(item, orgs);
                }
            }
        }

        public Results<IList<OrgListItemDTO>> GetCompanyNodeList(int? oid = null, bool toRoot = false)
        {
            if (CurrentUser.IsSuperAdmin && !oid.HasValue)
            {
                var companyList = _BIZ_OrganizationServices.GetCompanyTreeData(null);
                companyList = companyList.OrderBy(a => a.ID);
                var models = Mapper.Map<IList<OrgListItemDTO>>(companyList);
                return InfrastructureAppService.Response(models);
            }
            else if (CurrentUser.IsOrgAdmin && !oid.HasValue)
            {
                oid = CurrentUser.Current.ROID;
                var companyList = _BIZ_OrganizationServices.GetOrgDescendants(oid.Value, true);
                companyList = companyList.OrderBy(a => a.ID);
                var models = Mapper.Map<IList<OrgListItemDTO>>(companyList);
                return InfrastructureAppService.Response(models);
            }
            else
            {
                if (!oid.HasValue) oid = CurrentUser.Current.OID;
                if (toRoot) oid = CurrentUser.Current.ROID;
                var companyList = _BIZ_OrganizationServices.GetOrgDescendants(oid.Value, true);
                companyList = companyList.OrderBy(a => a.ID);
                var models = Mapper.Map<IList<OrgListItemDTO>>(companyList);
                return InfrastructureAppService.Response(models);
            }
        }

        #endregion


        public Results<List<AreaDTO>> GetAreaList()
        {
            var dto = new List<AreaDTO>();
            var expand = _ISysBasicServices.GetAreaList();
            AutoMapper.Mapper.Map(expand, dto, typeof(List<AreaExpand>), typeof(List<AreaDTO>));

            return InfrastructureAppService.Response(dto);
        }


        public Results<List<EnumItemDTO>> GetEnumItems(EnumKeyDTO enumKey)
        {
            List<EnumItemDTO> dtos = new List<EnumItemDTO>();
            Dictionary<int, string> dic = EnumHelper.GetFiledsDescriptionsByEnumKey(enumKey.EnumKey);
            foreach (int key in dic.Keys)
            {
                EnumItemDTO item = new EnumItemDTO();
                item.ItemValue = key;
                item.ItemName = dic[key];
                dtos.Add(item);
            }
            return InfrastructureAppService.Response(dtos);
        }

        /// <summary>
        /// bom 坐标等相关参数设置
        /// </summary>
        /// <param name="curUseID"></param>
        /// <param name="sysParamsDTO"></param>
        /// <returns></returns>
        public Results AddSysParamSettings(int curUseID,int oid,SysParamsDTO sysParamsDTO)
        {
            Sys_ParamSetting setting = new Sys_ParamSetting();
            setting.TagNoSplit = sysParamsDTO.TagNoSplit;
            setting.ContinueTagNoExplain = sysParamsDTO.ContinueTagNoExplain;
            setting.LossRateSet = JsonEx.SerializeObject(sysParamsDTO.MaterielLossRateParaDTO);
            setting.BarCodeSet = sysParamsDTO.BarCodeSet;  //BarCodeSolutionEnum
            setting.Creator = curUseID;
            setting.OID = oid;
            setting.CreateTime = DateTime.Now;
            setting.Updater = curUseID;
            setting.UpdateTime = DateTime.Now;
            _ISys_ParamSettingRepo.Add(setting);

            return InfrastructureAppService.Response();
        }

    }
}
